<script lang="ts" setup>
// #region 引入包, 函数和组件
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElLink,
  ElMessage,
  type FormInstance,
} from 'element-plus'
import { Check, Lock, User } from '@element-plus/icons-vue'
import { loginApi, captchaApi } from '@/business' // 登录接口
import { useUserStore } from '@/stores/userStore'
// #endregion

// #region // 使用模块(仓库、路由、父组件参数函数)
const router = useRouter()
const store = useUserStore()
// #endregion

// #region // 变量
const form = reactive({
  username: '',
  password: '',
  code: '',
})
const formRules = reactive({
  // 表单验证规则
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码长度为 4 个字符', trigger: 'blur' },
  ],
})
const backgroundImages = ref([
  // 背景图
  'https://picsum.photos/id/1035/1920/1080',
  'https://picsum.photos/id/1036/1920/1080',
  'https://picsum.photos/id/1037/1920/1080',
])
const currentBackgroundIndex = ref(0) // 背景图下标
const loginForm = ref<FormInstance | null>(null) // 表单实例
const captcha = ref('') // 随机验证码
const loginAllow = ref(false) // 允许点击登录
const code = ref('') // 验证码文字

// #endregion

// #region // 函数
const handleLogin = () => {
  if (!loginForm.value) {
    ElMessage.info('页面加载中, 请稍候重试...')
    return
  }
  // 这里需要添加表单验证逻辑
  loginForm.value.validate(async (valid) => {
    if (valid) {
      // 验证成功
      try {
        const res = await loginApi({
          username: form.username,
          password: form.password,
        })
        console.log(res)
        if (res.data.code === 0) {
          ElMessage.success('登录成功')
          store.setUser(res.data.data)
          console.log(store.user)
          router.push('/')
        } else {
          console.log('登录失败', res.data.msg)
        }
      } catch (error) {
        console.log(error)
      }
    } else {
      // 验证失败
      ElMessage.error('表单验证失败，请检查输入')
    }
  })
}
// 获取验证码
const getCaptcha = async () => {
  try {
    // 获取验证码
    const res = await captchaApi()
    if (res.status === 200) {
      captcha.value = String(res.data)
      code.value = res.headers['x-captcha']
    } else {
      ElMessage.error('获取验证码失败')
    }
  } catch (error) {
    console.log(error)
  }
}

const switchBackground = () => {
  currentBackgroundIndex.value = (currentBackgroundIndex.value + 1) % backgroundImages.value.length
}
// 验证验证码
const validataCode = () => {
  if (code.value === form.code.toUpperCase()) {
    // 允许登录
    loginAllow.value = true
    // 提示一下
    ElMessage.success('验证成功')
  } else {
    // 验证失误
    ElMessage.info('验证码错误')
    // 重新获取验证码
    getCaptcha()
  }
}
// #endregion

// #region // 生命周期和vue函数
onMounted(() => {
  // 设置背景图自动切换，每5秒切换一次
  setInterval(switchBackground, 5000)
})
// 进页面生成一次随机验证码
getCaptcha()
// #endregion
</script>

<template>
  <div
    class="login-container"
    :style="{ backgroundImage: `url(${backgroundImages[currentBackgroundIndex]})` }"
  >
    <div class="login-card">
      <div class="login-title">登录</div>
      <el-form :model="form" :rules="formRules" ref="loginForm" class="login-form">
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入账号"
            :prefix-icon="User"
            size="large"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>
        <el-form-item prop="code">
          <div class="code-container">
            <el-input v-model="form.code" placeholder="请输入验证码" size="large" />
            <div class="code-image" @click="getCaptcha" v-html="captcha"></div>
            <el-button @click="validataCode">验证</el-button>
          </div>
        </el-form-item>
        <el-form-item class="login-button">
          <el-button
            type="primary"
            size="large"
            class="login-btn"
            @click="handleLogin"
            :icon="Check"
            :disabled="!loginAllow"
          >
            确认登录
          </el-button>
        </el-form-item>
        <div class="register-link">
          <el-link type="primary" @click="router.push('/register')"> 没有账号？去注册 </el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style lang="sass" scoped>
.login-container
  min-height: 100vh;
  background-size: cover;
  background-position: center;
  transition: background-image 1s ease-in-out;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;

.login-card
  width: 100%;
  max-width: 420px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.15);
  padding: 30px;
  backdrop-filter: blur(8px);

.login-title
  text-align: center;
  font-size: 24px;
  font-weight: 600;
  color: #165dff;
  margin-bottom: 30px;

.login-form
  .el-form-item
    margin-bottom: 20px;

.code-container
  display: flex;
  gap: 10px;
  align-items: center

.code-image
  width: 120px;
  height: 40px;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  letter-spacing: 4px;
  cursor: pointer;
  user-select: none;
  color: #165dff;
  :deep(svg)
    width: 120px !important;
    height: 40px !important;

.login-button
  margin-top: 10px;

.login-btn
  width: 100%;
  background-color: #165dff;
  border-color: #165dff;

.register-link
  text-align: center;
  margin-top: 20px;
</style>
